
package com.csc440.team2.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


import com.csc440.team2.SmilConstants;
import com.csc440.team2.smil.SMILTextComponent;


/**
 * Activity to manage adding a text component to a message
 * 
 * @author Brad Gardner, Alex Povkov
 * 
 */
public class AddText extends Activity
{
    private String regionId;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.position_layout_text);

        Bundle bundle = getIntent().getExtras();
        regionId = bundle.getString(SmilConstants.REGION_ID);
    }


    /**
     * Adds a new component to the message and return to the calling activity
     * 
     * @param clickedView
     */
    public void returnToParent(View clickedView)
    {
        Intent data = new Intent();
        SMILTextComponent comp = SMILTextComponent.create();
        comp.setRegionId(regionId);

        String text = ((EditText) this.findViewById(R.id.EditText01)).getText().toString();
        String durationText = ((EditText) this.findViewById(R.id.EditText02)).getText().toString();
        String beginText = ((EditText) this.findViewById(R.id.EditText03)).getText().toString();

        if (isValid(text, durationText, beginText))
        {
            comp.setDuration(Integer.parseInt(durationText));
            comp.setBegin(Integer.parseInt(beginText));
            comp.setText(text);

            data.putExtra(SmilConstants.COMPONENT, comp);
            setResult(SmilConstants.COMPONENT_TYPE_TEXT, data);
            finish();
        }
    }


    private boolean isValid(String text, String durationText, String beginText)
    {
        boolean valid = true;

        String errorMessage = "";

        if (durationText == null || durationText.equals("") || !durationText.matches("[0-9]+"))
        {
            errorMessage += "Please enter a valid number in the Duration box.\n";
            valid = false;
        }
        if (beginText == null || beginText.equals("") || !beginText.matches("[0-9]+"))
        {
            errorMessage += "Please enter a valid number in the Begin Time box.\n";
            valid = false;
        }
        if (text == null || text.equals(""))
        {
            errorMessage += "Please enter text in the Insert Text box.\n";
            valid = false;
        }

        if (!valid)
            Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();

        return valid;
    }
}
